/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package vn.edu.vttu;

import com.sun.mail.pop3.POP3Store;
import java.awt.Color;
import java.awt.event.KeyEvent;
import static java.lang.System.out;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.swing.JOptionPane;


/**
 *
 * @author Lucas Nguyen
 */

public class Login extends javax.swing.JFrame {
       
            
         
    /**
     * Creates new form Login
     */
    public Login() {
        initComponents();
        trangthai.setBackground(Color.GREEN);
     trangthai.setStringPainted(true);
     this.setTitle("Đăng nhập");
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtuser = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtpw = new javax.swing.JPasswordField();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        trangthai = new javax.swing.JProgressBar();
        thongbao = new javax.swing.JLabel();

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAutoRequestFocus(false);
        setBackground(new java.awt.Color(255, 255, 255));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setLocationByPlatform(true);
        setUndecorated(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 153, 255));
        jLabel1.setText("Tên tài khoản ");

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 153, 255));
        jLabel2.setText("Mật khẩu");

        txtuser.setForeground(new java.awt.Color(51, 0, 0));
        txtuser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtuserActionPerformed(evt);
            }
        });
        txtuser.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtuserKeyPressed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(204, 153, 0));
        jLabel3.setText("Đăng nhập vào hộp thư Htmail");

        jLabel4.setForeground(new java.awt.Color(51, 51, 255));
        jLabel4.setText("@nhom5.no-ip.org");

        txtpw.setForeground(new java.awt.Color(51, 0, 0));
        txtpw.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtpwKeyPressed(evt);
            }
        });

        jButton2.setBackground(new java.awt.Color(255, 255, 255));
        jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon_homea[1].png"))); // NOI18N
        jButton2.setText("  Đăng nhập");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setBackground(new java.awt.Color(51, 153, 255));
        jButton3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/reboot lodo.jpg"))); // NOI18N
        jButton3.setText("   Hủy");
        jButton3.setHideActionText(true);
        jButton3.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        thongbao.setText("Nhập tài khoản và mật khẩu");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(62, 62, 62)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton2)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtpw, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(32, 32, 32)
                                .addComponent(txtuser, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addGap(0, 138, Short.MAX_VALUE))
            .addComponent(trangthai, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(132, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(thongbao)
                        .addGap(195, 195, 195))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(78, 78, 78))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(68, 68, 68))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtuser, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtpw, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(thongbao)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(trangthai, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtuserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtuserActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtuserActionPerformed

    // xác thực ------------
    public static void receiveEmail(String pop3Host, String storeType, String user, String password) {

		try {
			Properties properties = new Properties();
			properties.put("mail.pop3.host", pop3Host);
			Session emailSession = Session.getDefaultInstance(properties);

			POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
                                
                        emailStore.connect(pop3Host, user, password);
                        out.println("Kết nối thành công...");
                        
			//Folder emailFolder = emailStore.getFolder("INBOX");
                        
			//emailFolder.open(Folder.READ_ONLY);
                      //  out.println("Đang nạp hộp thư đến...");sinhvi
			//Message[] messages = emailFolder.getMessages();
                      //  System.out.print(messages.length);
                        
			

			//emailFolder.close(false);
			emailStore.close();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
                     
		}
                
                
		}
    // hàm xác thực
    
    public String kiemTraDiaChiGmail(String diaChi) {
        if (diaChi == null || diaChi.isEmpty()) {
            return null;
        }
        diaChi = diaChi.toLowerCase();
        
        if (diaChi.endsWith("@nhom5.no-ip.org")) {
            return diaChi;
        } else {
            if (diaChi.indexOf('@') < 0) {
                return diaChi.concat("@nhom5.no-ip.org");
            }
        }
        return null;
    }

    public boolean kiemTraRong(){
           ConnectionServer.userName = txtuser.getText();
            ConnectionServer.passWord=  txtpw.getText();
             if (ConnectionServer.userName == null || ConnectionServer.userName.equals("")) {
               JOptionPane.showMessageDialog(this, "Thiếu địa chỉ người gửi", "Error", JOptionPane.ERROR_MESSAGE);
               return  false;
             }
              if (ConnectionServer.passWord == null || ConnectionServer.passWord.length() == 0) {
          
                 JOptionPane.showMessageDialog(this, "Thiếu mật khẩu", "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
             
             return true;
    
    }
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here
           //jButton2.setVisible(false);
       // jButton2.setEnabled(false);
     
          
              ConnectionServer.userName = txtuser.getText();
                ConnectionServer.passWord=  txtpw.getText();
            
              if(kiemTraRong()){
              if(kiemTraDiaChiGmail(ConnectionServer.userName) != null){
      try {
           thongbao.setText("Đang thử kết nối....");
			Properties properties = new Properties();
			properties.put("mail.pop3.host", ConnectionServer.mailHost);
			Session emailSession = Session.getDefaultInstance(properties);

			POP3Store emailStore = (POP3Store) emailSession.getStore(ConnectionServer.mailStoreType);
                                
                        emailStore.connect(ConnectionServer.mailHost, kiemTraDiaChiGmail(ConnectionServer.userName), ConnectionServer.passWord);
                        out.println("Kết nối thành công...");
                        
                        thongbao.setText("Kết nối thành công..");
                        trangthai.setVisible(true);
                        
			Folder emailFolder = emailStore.getFolder("INBOX");
                        emailFolder.open(Folder.READ_ONLY);
                         thongbao.setText("Đang nạp hộp thư đến...");       
                        Message[] messages = emailFolder.getMessages();
                           for (int i = 0; i < messages.length; i++) {
                    
                             trangthai.setValue(i * 100 / messages.length);
                           }
                      int yes=   JOptionPane.showConfirmDialog(null,"Kết nối thành công. Có "+messages.length+" thư trong hộp thư đến","Thông báo",JOptionPane.YES_OPTION,JOptionPane.INFORMATION_MESSAGE);
                        // thongbao.setText("Loading.....");
                         
                     if(yes==JOptionPane.YES_OPTION){
                        emailFolder.close(false);
			emailStore.close();
			MainLayer main = new MainLayer();
                        
                        
                        main.setTitle("Htmail Express");
                        main.setVisible(true);
                        this.setVisible(false);
                 }
                     else{
                      emailFolder.close(false);
			emailStore.close();
			MainLayer main = new MainLayer();
                        main.setVisible(true);
                        this.setVisible(false);
                     }
                      //  System.out.print(messages.length);
                        

			
		} catch (NoSuchProviderException e) {
                 e.printStackTrace();
               
                 thongbao.setText("Không thế kết nối đến Server. Hãy kiểm tra lại tại khoản hoặc mật khẩu....");
		} catch (MessagingException e) {
			e.printStackTrace();
                thongbao.setText("Hảy kiểm tra lại đường truyền Internet của bạn...");
                     
		}
                
         // JOptionPane.showConfirmDialog(null, "Không thể kết nối đến server & port...","Lỗi",JOptionPane.YES_NO_OPTION,JOptionPane.ERROR_MESSAGE);

              }
              else {
              JOptionPane.showMessageDialog(null, ConnectionServer.userName + " không phải là địa chỉ nhom5.no-ip.org", "Error", JOptionPane.ERROR_MESSAGE);
                return;
              }// kết thúc hàm kiểm tra địa chỉ mail
              
              }// kết thúc hàm kiểm tra rổng
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        System.exit(5);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void txtuserKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtuserKeyPressed
            // TODO add your handling code here:
      if (evt.getKeyCode() == KeyEvent.VK_ENTER)
      { 
          txtpw.requestFocus();
      }
    }//GEN-LAST:event_txtuserKeyPressed

    private void txtpwKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtpwKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
      { 
          jButton2.doClick();
      }
    }//GEN-LAST:event_txtpwKeyPressed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
       this.setLocationRelativeTo(null); 
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel thongbao;
    private javax.swing.JProgressBar trangthai;
    private javax.swing.JPasswordField txtpw;
    private javax.swing.JTextField txtuser;
    // End of variables declaration//GEN-END:variables
}
